<?php

/**
 * 每天生成一次 品牌卡片上 10条note，分类及住友喜欢图像信息
 */

ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\cache\brand\BrandResumeInfo;
use Biz\model\brand\Brand as mBrand;
use Biz\model\brand\Content as mBrandContent;
use Biz\model\ShopCategoryClassify as mShopCategoryClassify;
use Biz\model\wiki\Wiki as mWiki;
use Biz\module\Classes\wiki\Wiki as clsWiki;
use Doraemon\cache\PhotoCounter;
use Doraemon\model\Member;
use Doraemon\service\Photos as sPhotos;
use Doraemon\service\User;
use Doraemon\tools\BlockType;
use Doraemon\tools\IdParse;

//品牌设置为「精选内容」的住友发布的内容 note
//取交互数 从高到低
$start = time();
$page = 1;
$pageSize = 400;
$brandList = [];
do {
    $where = ['status' => mBrand::STATUS_USING, 'LIMIT' => [($page - 1) * $pageSize, $pageSize]];
    $brandList = mBrand::selectByWhere($where);
    var_dump(mBrand::log());
    if ($brandList) {
        $brandIds = array_column($brandList, 'id');
        $brandContentList = mBrandContent::select('*', ['brand_id' => $brandIds, 'obj_type' => BlockType::TYPE_PHOTO, 'is_selected' => 1]);
        $noteIds = [];
        $brandSelectContent = [];
        foreach ($brandContentList as $row) {
            $noteIds[] = $row['obj_id'];
            $brandSelectContent[$row['brand_id']][] = $row['obj_id'];
        }
        $noteIds = array_unique($noteIds);
        $photoCounter = PhotoCounter::getMulti($noteIds);
        $note_list = sPhotos::getPhotos($noteIds, 0);
        foreach ($brandList as $row) {
            $brandId = $row['id'];
            $brandName = $row['brand_name'];
            $brandAlias = $row['brand_alias'] ? json_decode($row['brand_alias'], true) : [];
            $category = getBrandSecondCategory($brandId);
            $remarks = [];
            if (isset($brandSelectContent[$brandId])) {
                foreach ($brandSelectContent[$brandId] as $noteId) {
                    if (isset($note_list[$noteId])) {
                        $remark = $note_list[$noteId]['remark'];
                        $remark = str_replace(["\r\n", "\r", "\n"], "", $remark);
                        $content = subContent($remark, $brandName, $brandAlias);
                        $count = 0;
                        if (isset($photoCounter[$noteId])) {
                            $count = $photoCounter[$noteId]['like'] + $photoCounter[$noteId]['favorite'];
                        }
                        if ($content) {
                            $remarks[$noteId] = [
                                'content' => $content,
                                'count' => $count
                            ];
                        }
                    }
                }
            }
            $selectContent = [];
            foreach ($remarks as $noteId => $remarkInfo) {
                $content = $remarkInfo['content'];
                $uid = IdParse::getUid($noteId);
                $memberList = Member::getUserInfoByIds([$uid]);
                $memberInfo = $memberList ? array_shift($memberList) : [];
                $avatarImg = '';
                if ($memberInfo) {
                    $avatarImg = User::getUserAvatarPicUrl($memberInfo['uid'], $memberInfo['avatar_version']);
                    if ($avatarImg) {
                        $avatarImg = $avatarImg[0];
                    }
                }
                if (!$avatarImg) {
                    var_dump('查询不到内容所属的用户图像#uid:' . $uid . '#note_id:' . $noteId . '#memberinfo' . json_encode($memberInfo, JSON_UNESCAPED_UNICODE));
                    continue;
                }
                $selectContent[] = [
                    'avatar' => $avatarImg,
                    'content' => $content,
                    'count' => $remarkInfo['count']
                ];
            }
            if ($selectContent) {
                $sortCount = array_column($selectContent, 'count');
                array_multisort($sortCount, SORT_DESC, $selectContent);
            }
            setResumeInfo($brandId, $category, $selectContent);
        }
    }
    $page++;
} while ($brandList);
$end = time();
var_dump(date('Y-m-d-H-i-s') . '耗时:' . ($end - $start) . '秒，' . (($end - $start) / 60) . '分');

function getBrandSecondCategory($brandId)
{
    //取该品牌商品库中所有商品所对应的前端二级类目名称
    $arr = mWiki::selectByWhere(['brand_id' => $brandId, 'is_official' => 1], ['category_id', 'second_category_id', 'third_category_id', 'four_category_id']);
    $categoryIds = [];
    foreach ($arr as $row) {
        $categoryIds[] = $row['category_id'];
        $categoryIds[] = $row['second_category_id'];
        $categoryIds[] = $row['third_category_id'];
        $categoryIds[] = $row['four_category_id'];
    }
    $categoryIds = array_unique($categoryIds);
    $ids = mShopCategoryClassify::select('parent_id', ['cate_id' => $categoryIds, 'cate_id[>]' => 0, 'status' => mShopCategoryClassify::STATUS_NORMAL]);
    $cateNames = mShopCategoryClassify::select('classify_name', ['id' => $ids, 'deep' => 2]);
    $category = $cateNames ? implode('|', $cateNames) : '';
    return $category;
}


function setResumeInfo($brandId, $category, $selectContent)
{
    var_dump('更新品牌的卡片信息:' . $brandId);
    $fans = clsWiki::getRandUserCoverImg(3);
    $fans = array_column($fans, 'cover_img');
    if ($category || $selectContent || $fans) {
        $resumeInfo = [
            'category' => $category,
            'select_content' => $selectContent,
            'fans' => $fans
        ];
        $resumeInfo['brand_id'] = $brandId;
        BrandResumeInfo::setResumeInfo($brandId, $resumeInfo);
    }
}

function subContent($remark, $brandName, array $brandAlias)
{
    $content = '';
    if ($remark) {
        //截取内容，如果包含 品牌名或则品牌别称，从品牌名开始截取20个字符，否则从内容开始部分截取20个字符
        $content = mb_substr($remark, mb_strpos($remark, $brandName), 30, 'utf-8');
        if (mb_strpos($remark, $brandName) === FALSE) {
            foreach ($brandAlias as $alias) {
                if (mb_strpos($remark, $alias) !== FALSE) {
                    $content = mb_substr($remark, mb_strpos($remark, $alias), 30, 'utf-8');
                    break;
                }
            }
        }
    }
    return $content;
}